<template>
  <a-form
    :model="queryParams"
    layout="inline"
    autocomplete="off"
    @finish="onFinish"
    class="s-search"
  >
    <a-row class="s-search-row">
      <a-col class="s-search-col">
        <a-form-item :label="t('sysAccount26')">
          <a-input
            allowClear
            v-model:value="queryParams.username"
            :placeholder="t('placeholder125')"
            v-input.trim.textFilter
          />
        </a-form-item>
        <a-form-item :label="t('sysAccount27')">
          <a-select
            allowClear
            style="width: 180px"
            v-model:value="queryParams.role_id"
            :placeholder="t('placeholder127')"
            :options="roleOptions"
          ></a-select>
        </a-form-item>

        <a-form-item :label="t('table31')">
          <a-select
            allowClear
            style="width: 180px"
            v-model:value="queryParams.status"
            :placeholder="t('placeholder61')"
            :options="staffStatusMap"
          ></a-select>
        </a-form-item>
        <a-form-item>
          <a-space :size="16">
            <a-button type="primary" html-type="submit">
              {{ t("base.query") }}
              <template #icon><search-outlined /></template>
            </a-button>
            <a-button type="default" @click="handleReset">
              {{ t("base.reset") }}
              <template #icon><delete-outlined /></template>
            </a-button>
          </a-space>
        </a-form-item>
      </a-col>

      <a-col>
        <a-button
          v-has="'accountApi.create'"
          type="primary"
          @click="handleAction({ type: 'add' })"
          :loading="addLoading"
        >
          <template #default>
            {{ t("base.add") }}
          </template>
          <template #icon>
            <i
              :class="`s-icon iconfont ${getSelfNodeIcon('accountApi.create')}`"
            />
          </template>
        </a-button>
      </a-col>
    </a-row>
  </a-form>

  <a-table
    class="s-table"
    :pagination="tablePage"
    :columns="columns"
    :data-source="dataSource"
    @change="handleTableChange"
    :loading="tableLoading"
  >
    <template v-slot:bodyCell="{ value, text, index, column, record }">
      <template v-if="column.key === 'index'">
        <i>{{ index + 1 + (tablePage.current - 1) * tablePage.pageSize }}</i>
      </template>

      <template v-if="column.key === 'status'">
        <i :class="record.status === 0 ? 's-52c41a' : 's-c1c1c1'">{{
          selectDictLabel(staffStatusMap, record.status)
        }}</i>
      </template>

      <template v-if="column.key === 'action'">
        <div class="s-table-body_cell">
          <div v-has="'accountApi.updateStatus'">
            <a-button
              type="link"
              @click="handleAction({ type: 'update->status', record })"
              >{{ record.status === 0 ? t("base.disable") : t("base.enable") }}
              <template #icon>
                <i
                  :class="`s-icon iconfont ${
                    getSelfNodeIcon('accountApi.updateStatus')
                      ? record.status === 0
                        ? 'icon-qiyong'
                        : 'icon-tingyong'
                      : ''
                  }`"
                /> </template
            ></a-button>
            <a-divider type="vertical" />
          </div>
          <div v-has="'accountApi.update'">
            <a-button
              type="link"
              @click="handleAction({ type: 'edit', record })"
              >{{ t("base.edit") }}
              <template #icon>
                <i
                  :class="`s-icon iconfont ${getSelfNodeIcon(
                    'accountApi.update'
                  )}`"
                /> </template
            ></a-button>
            <a-divider type="vertical" />
          </div>
          <div v-has="'accountApi.delete'">
            <a-button
              type="link"
              @click="handleAction({ type: 'delete', record })"
              >{{ t("base.delete") }}
              <template #icon>
                <i
                  :class="`s-icon iconfont ${getSelfNodeIcon(
                    'accountApi.delete'
                  )}`"
                /> </template
            ></a-button>
            <a-divider type="vertical" />
          </div>
          <a-button
            type="link"
            v-has="'accountApi.updatePsd'"
            @click="handleAction({ type: 'update->password', record })"
            >{{ t("base.changePsd") }}
            <template #icon>
              <i
                :class="`s-icon iconfont ${getSelfNodeIcon(
                  'accountApi.updatePsd'
                )}`"
              /> </template
          ></a-button>
        </div>
      </template>
    </template>
  </a-table>
  <IMFormInline
    ref="drawerRef"
    @refreshTable="refreshTable"
    @fetchList="fetchList"
    :roleOptions="roleOptions"
  />
  <IMModal ref="modalRef" @refreshTable="refreshTable" />
</template>
<script lang="ts">
import {
  tableLoading,
  modalFormInline,
  tablePage,
  searchParams,
  staffStatusMap,
  addLoading,
  roleOptions,
  modalInputValidators,
  drawerInputValidators,
} from "./store";
import { fetchRoleDict } from "./utils";
import IMFormInline from "./components/drawer/index.vue";
import IMModal from "./components/modal/index.vue";
import { IMTableType } from "@/types/table";
import { getSelfNodeIcon } from "@system/menu/store";
import { QueryParamsType } from "./type";
const columns = reactive<IMTableType[]>(
  defineColumns([
    {
      title: getProxyT("base.index"),
      dataIndex: "index",
      key: "index",
    },
    {
      title: getProxyT("table189"),
      dataIndex: "username",
      key: "username",
    },
    { title: "员工姓名", dataIndex: "name", key: "name", align: "center" },
    {
      title: getProxyT("table190"),
      dataIndex: "role_name",
      key: "role_name",
    },
    {
      title: getProxyT("table31"),
      dataIndex: "status",
      key: "status",
    },
    {
      title: computed(() => `${$t("table191")}ip`),
      dataIndex: "last_login_ip",
      key: "last_login_ip",
    },
    {
      title: getProxyT("table19"),
      dataIndex: "last_login_time",
      key: "last_login_time",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    { title: getProxyT("base.action"), key: "action", align: "center" },
  ])
);

export default defineComponent({
  components: {
    IMFormInline,
    IMModal,
  },
  setup() {
    let dataSource: any = ref([]);
    const drawerRef = ref<any>(null);
    const modalRef = ref<any>(null);
    const queryParams = reactive<QueryParamsType>({
      username: undefined,
      role_id: undefined,
      status: undefined,
    });
    const handleReset = () => {
      clearObjAttr(queryParams);
      refreshTable();
    };
    const onFinish: any = (values: any) => {
      onFinish.timer && clearTimeout(onFinish.timer);
      onFinish.timer = setTimeout(() => refreshTable(), 200);
    };
    const fetchList = async () => {
      try {
        tableLoading.value = true;
        dataSource.value = [];
        const res: any = await accountApi.query({
          page: tablePage.current,
          page_size: tablePage.pageSize,
          ...searchParams,
        });
        if (res.code != 200) return message.error(res.message);
        dataSource.value = res?.data?.list ?? [];
        tablePage.total = res?.data?.attributes?.total ?? 0;
      } catch (error: any) {
        message.error(error.message);
      } finally {
        tableLoading.value = false;
      }
    };
    const refreshTable = async () => {
      tablePage.current = 1;
      initObjAttr(searchParams, queryParams);
      searchParams.status =
        +searchParams.status === Infinity ? undefined : searchParams.status;
      await fetchList();
    };

    const handleTableChange = (paging: any) => {
      tablePage.current = paging.current;
      tablePage.pageSize = paging.pageSize;
      fetchList();
    };
    const handleChange = (value: string) => {};
    const handleDelete = (record: { id: any }) => {};
    const handleAction = async ({ record, type }: any) => {
      initObjAttr(modalInputValidators, createArray(false, 2));
      initObjAttr(drawerInputValidators, createArray(false, 3));
      if (type === "delete") {
        Modal.confirm({
          closable: true,
          title: $t("sysAccount35"),
          content: `${$t("sysAccount36")}${record.name}${$t("sysAccount37")}`,
          icon: null,
          maskClosable: true,
          centered: true,
          async onOk() {
            try {
              const res: any = await accountApi.delete({
                id: record.id,
              });
              if (res.code != 200) return message.error(res.message);
              refreshTable();
              message.success($t("base.deleteSuccess"));
            } catch (error: any) {
              message.error(error.message);
            } finally {
            }
          },
          cancelText: $t("base.cancel"),
          onCancel() {
            Modal.destroyAll();
          },
        });
        return;
      }

      if (type === "update->password") {
        modalRef.value.title = `${$t("sysAccount34")}(${record.name})`;
        clearObjAttr(modalFormInline);
        modalFormInline.id = record.id;
        modalRef.value.showModal();
        return;
      }
      if (type === "edit" || type === "add") {
        drawerRef.value.showDrawer(type, record);
        return;
      }

      if (type === "update->status") {
        Modal.confirm({
          closable: true,
          icon: null,
          maskClosable: true,
          title: () => $t("sysAccount33"),
          style: {
            top: "30%",
          },
          content:
            record.status === 0
              ? `${$t("sysAccount29")}${record.name}${$t("sysAccount31")}`
              : `${$t("sysAccount30")}${record.name}${$t("sysAccount32")}`,
          onOk: async () => {
            const res = reactive<any>(
              await accountApi.updateStatus({
                id: record.id,
                status: +record.status === 0 ? 1 : 0,
              })
            );
            if (res.code != 200) return message.error(res.message);
            message.success($t("base.updateSucess"));
            fetchList();
          },
        });
        return;
      }
    };
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    onActivated(() => {
      fetchRoleDict();
      fetchList();
    });
    return {
      handleAction,
      getSelfNodeIcon,
      t: $t,
      fetchList,
      refreshTable,
      roleOptions,
      tablePage,
      drawerRef,
      modalRef,
      handleDelete,
      handleChange,
      handleTableChange,
      dataSource,
      columns,
      queryParams,
      onFinish,
      handleReset,
      staffStatusMap,
      selectDictLabel,
      tableLoading,
      addLoading,
    };
  },
});
</script>

<style scoped lang="less">
.im-input-group.im-input-group-compact {
  display: flex;
}
</style>
